package ferp.android.layouts;

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.LinearLayout;

/**
 * User: igorgok
 * Date: 1/1/14 3:32 PM
 */
public abstract class LayoutBase extends ViewGroup
{
  public LayoutBase(Context context)
  {
    super(context);
  }

  public LayoutBase(Context context, AttributeSet attrs)
  {
    super(context, attrs);
  }

  public LayoutBase(Context context, AttributeSet attrs, int defStyle)
  {
    super(context, attrs, defStyle);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
  {
    int mx = MeasureSpec.getMode(widthMeasureSpec), my = MeasureSpec.getMode(heightMeasureSpec);
    int sx = MeasureSpec.getSize(widthMeasureSpec), sy = MeasureSpec.getSize(heightMeasureSpec);

    //Log.debug(Log.TAG, "LB measure: " + GUI.m2s(mx) + ' ' + sx + ", " + GUI.m2s(my) + ' ' + sy);

    if (mx == MeasureSpec.AT_MOST && my == MeasureSpec.AT_MOST)
    {
      onMeasureUnspecified(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);

      setMeasuredDimension(Math.min(sx, getMeasuredWidth()), Math.min(sy, getMeasuredHeight()));
    }
    else
      if (mx == MeasureSpec.UNSPECIFIED && my == MeasureSpec.UNSPECIFIED)
        onMeasureUnspecified(widthMeasureSpec, heightMeasureSpec);
      else
        onMeasureExactly(sx, sy);
  }

  protected abstract void onMeasureUnspecified(int widthMeasureSpec, int heightMeasureSpec);
  protected abstract void onMeasureExactly(int sx, int sy);

  @Override
  public LayoutParams generateLayoutParams(AttributeSet attrs) {return new LinearLayout.LayoutParams(getContext(), attrs);}
  @Override
  protected LayoutParams generateDefaultLayoutParams() {return new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);}
  @Override
  protected LayoutParams generateLayoutParams(LayoutParams p) {return new LinearLayout.LayoutParams(p);}
  @Override
  protected boolean checkLayoutParams(LayoutParams p) {return p instanceof LinearLayout.LayoutParams;}
}
